'use strict';
import React, { PropTypes } from 'react';
import {View,Text,Modal,Dimensions,Picker,StyleSheet,TouchableOpacity,Platform} 
        from 'react-native';

import Common from '../common/constants';


const isIos = Platform.OS === 'ios';

export default class RegionSelect extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
                  isVisible: false,

                  provinces: [],
                  citys: [],
                  areas: [],

                  selectedProvince: this.props.selectedProvince,
                  selectedCity: this.props.selectedCity,
                  selectedArea: this.props.selectedArea,

                  transparent: true,
                  initArea:this.props.initArea
    };

  }

  componentDidMount() 
  {
    let provinces=this.state.initArea!=undefined?this.state.initArea:[];
    
    console.log('provinces:'+JSON.stringify(provinces));
    let citys=provinces[0].citys!=undefined?provinces[0].citys:[];

    let select={'provinces':provinces,'citys':citys};
    select['selectedProvince']=(provinces.length>0&&provinces[0].province!=undefined)?provinces[0].province:'';
    select['selectedCity']=(citys.length>0&&citys[0].city!=undefined)?citys[0].city:'';

    this.setState(select);
  }


  componentWillReceiveProps(props) {
    if (props.isVisible !== this.props.isVisible) {
      if (props.isVisible) {
        this.open();
      } else {
        this.close();
      }
    }
  }

  close() {
    this.setState({ isVisible: false });
  }
  open() {
    this.setState({ isVisible: true });
  }

  _handleProvinceChange(province) {
    let provinces=this.state.provinces;
    let select={'areas':[]}; 
    for (var i = provinces.length - 1; i >= 0; i--) {
        if(province==provinces[i].province)
        {
            select['selectedProvince']=province;
            
            let citys=provinces[i].citys!=undefined?provinces[i].citys:[];
            select['selectedCity']=(citys.length>0&&citys[0].city!=undefined)?citys[0].city:'';
            select['citys']=citys;
            if(citys.length>0&&citys[0].areas!=undefined)
            {
                select['areas']=citys[0].areas;
                if(citys[0].areas[0]!=undefined)
                select['selectedArea']=citys[0].areas[0];
            }
            this.setState(select);
            break;
        }
    }
  }


  _handleCityChange(city) {

    let citys=this.state.citys;
    let select={'areas':[]}; 
    for (var i = citys.length - 1; i >= 0; i--) 
    {

        if(city==citys[i].city)
        {
            
            select['selectedCity']=city;
            console.log('selectedCity:'+city);
            select['areas']=(citys[i].areas!=undefined&&citys[i].areas.length>0)?citys[i].areas:[];
            select['selectedArea']=(select['areas'].length>0&&select['areas'][0].area!=undefined)?select['areas'][0].area:'';
            this.setState(select);
            break;
        }
    }

  }


  _handleAreaChange(area) {
    console.log('area:'+area);
    this.setState({
      selectedArea: area,
    });
  }

  _handleCancel() {
    if (this.props.onCancel) {
      this.props.onCancel();
    }
    this.close();
  }

  _handleSubmit() {
    if (this.props.onSubmit) 
    {
        let provinceName='';
        let cityName='';
        let areaName='';
        for (var i = this.state.provinces.length - 1; i >= 0; i--) {
            if(this.state.provinces[i].province==this.state.selectedProvince){
                provinceName=this.state.provinces[i].provinceName;
                break;
            }
        }
        for (var i = this.state.citys.length - 1; i >= 0; i--) {
            if(this.state.citys[i].city==this.state.selectedCity){
                cityName=this.state.citys[i].cityName;
                break;
            }
        }
        for (var i = this.state.areas.length - 1; i >= 0; i--) {
            if(this.state.areas[i].area==this.state.selectedArea){
                areaName=this.state.areas[i].areaName;
                break;
            }
        }

      this.props.onSubmit(
        [{'name':'province','value':provinceName},
         {'name':'city',    'value':cityName},
         {'name':'area',    'value':areaName}]

        // province: {province:this.state.selectedProvince,provinceName:provinceName},
        // city: {city:this.state.selectedCity,cityName:cityName},
        // area: {area:this.state.selectedArea,areaName:areaName},
      );
    }
    this.close();
  }
  

  renderPicker() {
    const { navBtnColor } = this.props;
    return (
      <View style={styles.overlayStyle}>
        <View style={[styles.pickerContainer, isIos ? {} : { marginTop: Common.window.height - 80 - this.props.androidPickerHeight }]}>
          
          <View style={styles.navWrap}>
            <TouchableOpacity
              style={[styles.navBtn, { borderColor: navBtnColor }]}
              activeOpacity={0.85}
              onPress={this._handleCancel.bind(this)}>
              <Text style={[styles.text, { color: navBtnColor }]}>取消</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.navBtn, { backgroundColor: navBtnColor, borderColor: navBtnColor }]}
              activeOpacity={0.85}
              onPress={this._handleSubmit.bind(this)}
            >
              <Text style={[styles.text, { color: 'white' }]}>确认</Text>
            </TouchableOpacity>
          </View>


          <View style={styles.pickerWrap}>

            <Picker style={styles.pickerItem}
              onValueChange={this._handleProvinceChange.bind(this)}
              selectedValue={this.state.selectedProvince}
            >
              {this.state.provinces.map((itemProvince, index) => {
                return (
                  <Picker.Item value={itemProvince.province} label={itemProvince.provinceName} key={index} />
                );
              })}
            </Picker>

            <Picker style={styles.pickerItem}
              onValueChange={this._handleCityChange.bind(this)}
              selectedValue={this.state.selectedCity}
            >
              {this.state.citys.map((itemCity, index) => {
                return (
                  <Picker.Item value={itemCity.city} label={itemCity.cityName} key={index} />
                );
              })}
            </Picker>

            <Picker style={styles.pickerItem}
              onValueChange={this._handleAreaChange.bind(this)}
              selectedValue={this.state.selectedArea}
            >
              {this.state.areas.map((areaItem, index) => {
                return (
                  <Picker.Item value={areaItem.area} label={areaItem.areaName} key={index} />
                );
              })}
            </Picker>

          </View>
        </View>
      </View>
    );
  }

  render() {
    const modal = (
      <Modal
        transparent={this.state.transparent}
        visible={this.state.isVisible}
        onRequestClose={this.close}
        animationType={this.props.animationType}
      >
        {this.renderPicker()}
      </Modal>
    );

    return (
      <View>
        {modal}
        <TouchableOpacity onPress={this.open.bind(this)}>
          {this.props.children}
        </TouchableOpacity>
      </View>
    );
  }
}
 
 

const styles = StyleSheet.create({
  overlayStyle: {
    flex: 1,
    width: Common.window.width,
    height: Common.window.height,
    left: 0,
    position: 'absolute',
    backgroundColor: 'rgba(0, 0, 0, 0.65)',
  },
  pickerContainer: {
    flex: 1,
    marginTop: Common.window.width * 3 / 5,
    backgroundColor: '#FFF'
  },
  navWrap: {
    paddingHorizontal: 15,
    paddingVertical: 8,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderTopWidth: 1,
    borderColor: '#ccc'
  },
  navBtn: {
    paddingVertical: 5,
    paddingHorizontal: 20,
    borderWidth: 1,
    borderRadius: 4
  },
  text: {
    fontSize: 18,
  },
  pickerWrap: {
    flexDirection: 'row'
  },
  pickerItem: {
    flex: 1
  }
});
